package com.w3c.pragmatic.test;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

// ==================================================
<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>2.0.27</version>
</dependency>
// ==================================================
通过pdf2htmlEX将pdf转成html并上传到oss
// ==================================================

@Slf4j
@Service
public class Pdf2HtmlEXUtil {

  private final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
  private final String accessKeyId = "LTAI5t5kMNiMSZSXDr9hCFJM";
  private final String accessKeySecret = "quhH9TCrg64EIiLmEv7saRfNNVeZMw";
  private final String bucketName = "channel-asset-access";
  private final String convertedPath = "test/agreement/html/converted/";
  private final String accessPrefix = "https://channel-oss-cdn.xiaoxiangyoupin.cn/";

  /**
   * 将 OSS 上的 PDF 文件转换为 HTML
   *
   * @param inputPdfPath OSS 上 PDF 文件的 key
   * @return 转换后的 HTML 文件 URL
   */
  public String convertPdfToHtml(String inputPdfPath) throws IOException, InterruptedException {
    // 创建临时目录
    String random = UUID.randomUUID().toString();
    String tempDir = System.getProperty("user.dir") + "/pdf2html_" + random;
    Path tempDirPath = Paths.get(tempDir);
    Files.createDirectories(tempDirPath);
    try {
      // 1. 从 OSS 下载 PDF 文件
      String tempLocalPdfPath = tempDir + "/input.pdf";
      downloadFileFromOss(inputPdfPath, tempLocalPdfPath);

      // 2. 使用 pdf2htmlEX 转换 PDF 为 HTML
      String tempLocalHtmlPath = tempDir + "/output.html";
      convertWithPdf2HtmlEx(tempLocalPdfPath, tempLocalHtmlPath);

      // 3. 上传 HTML 文件到 OSS
      String outputHtmlPath = convertedPath + random + "_output.html";
      uploadFileToOss(tempLocalHtmlPath, outputHtmlPath);

      // 4. 返回 HTML 文件的访问 URL
      return accessPrefix + outputHtmlPath;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      // 清理临时文件
      deleteDirectory(tempDirPath.toFile());
    }
  }

  private void downloadFileFromOss(String objectKey, String localFilePath) throws Exception {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
      OSSObject ossObject = ossClient.getObject(bucketName, objectKey);
      try (InputStream inputStream = ossObject.getObjectContent();
          FileOutputStream fileOutputStream = new FileOutputStream(localFilePath)) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
          fileOutputStream.write(buffer, 0, len);
        }
      }
    } finally {
      ossClient.shutdown();
    }
  }

  private void convertWithPdf2HtmlEx(String pdfPath, String htmlPath)
      throws IOException, InterruptedException {
    // 构建转换命令
    ProcessBuilder processBuilder =
        new ProcessBuilder("pdf2htmlEX", "--zoom", "1", pdfPath, htmlPath);
    /*ProcessBuilder processBuilder =
            new ProcessBuilder(
                    "pdf2htmlEX",
                    "--zoom", "1",               // 适当缩放
                    "--embed-css", "1",         // 嵌入 CSS
                    "--embed-font", "1",        // 嵌入字体
                    "--embed-image", "1",       // 嵌入图片
                    "--embed-javascript", "1",  // 嵌入 JavaScript
                    "--optimize-text", "1",     // 优化文本
                    "--process-outline", "1",   // 处理大纲
                    pdfPath,
                    htmlPath);*/
    // 执行命令
    Process process = processBuilder.start();

    // 读取错误流，方便调试
    try (BufferedReader errorReader =
        new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
      String line;
      while ((line = errorReader.readLine()) != null) {
        System.err.println(line);
      }
    }

    int exitCode = process.waitFor();
    if (exitCode != 0) {
      throw new IOException("pdf2htmlEX 转换失败，退出码: " + exitCode);
    }
  }

  private void uploadFileToOss(String localFilePath, String objectKey) {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
      ossClient.putObject(bucketName, objectKey, new File(localFilePath));
    } finally {
      ossClient.shutdown();
    }
  }

  private void deleteDirectory(File directory) {
    if (directory.exists()) {
      File[] files = directory.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file.isDirectory()) {
            deleteDirectory(file);
          } else {
            boolean delete = file.delete();
            log.info("删除临时文件===>{}", delete);
          }
        }
      }
      boolean delete = directory.delete();
      log.info("删除临时文件夹===>{}", delete);
    }
  }

  public static void main(String[] args) {
    // 示例用法
    Pdf2HtmlEXUtil converter = new Pdf2HtmlEXUtil();

    try {
      String htmlUrl =
          converter.convertPdfToHtml("test/agreement/template/2023013019794260636532736.pdf");
      System.out.println("转换成功，HTML URL: " + htmlUrl);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
